package com.smit.livevideo.sample.fragment;

import java.util.HashMap;
import java.util.Map;

import android.app.Activity;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.view.KeyEvent;
import android.view.View;

import com.smit.utils.LogUtil;

/**
 * Created by smfang on 2015/11/24. Fragment工具类，接受fragment的所有调用处理
 */
public final class FragmentUtil
{
    private static final String TAG = FragmentUtil.class.getSimpleName();
    private static Map<String, BaseFragment> fragmentsMap = new HashMap<String, BaseFragment>();
    private static BaseFragment lastFragment;

    private FragmentUtil()
    {

    }

    /**
     * 获取搜台fragment对象
     * @return BaseFragment
     */
    public static BaseFragment getSearchProgressFragment()
    {
        BaseFragment fSearchProgressFragment = fragmentsMap.get("fSearchProgressFragment");
        if (fSearchProgressFragment == null)
        {
            fSearchProgressFragment = new ScanServicesFragment();
            fragmentsMap.put("fSearchProgressFragment", fSearchProgressFragment);
        }
        return fSearchProgressFragment;
    }

    /**
     * 释放map中所有的fragment
     */
    public static void releaseFragments()
    {
        fragmentsMap.clear();
    }

    /**
     * int 0:按键可以由activity处理; 1:按键不让acitivity处理，并且return true给系统（系统不作处理）;
     * 2:按键不让acitivity处理，并且return false给系统（系统做默认处理）;
     * @param activity Activity对象
     * @param keyCode 键值
     * @param event 按键事件
     * @return int
     */
    public static int onKeyDown(Activity activity, int keyCode, KeyEvent event)
    {
        LogUtil.debug(TAG, "onKeyDown: lastFragment is " + lastFragment);
        if (activity == null || event == null)
        {
            LogUtil.error(TAG, "onKeyDown activity or event is null");
            return 0;
        }
        LogUtil.debug(TAG, event.toString());

        if (lastFragment != null)
        {
            LogUtil.debug(TAG, "lastFragment is not null");
            if (lastFragment.isVisible())
            {
                LogUtil.debug(TAG, "lastFragment is visible");
                return lastFragment.onKeyDown(keyCode, event);
            }
        }
        return 0;
    }

    /**
     * 设置随后一个fragment
     * @param fgmt BaseFragment对象
     */
    public static void setLastFragment(BaseFragment fgmt)
    {
        lastFragment = fgmt;
    }

    /**
     * 获取最后一个fragment
     * @return BaseFragment
     */
    public static BaseFragment getLastFragment()
    {
        LogUtil.debug(TAG, "lastFragment is " + lastFragment);
        return lastFragment;
    }

    /**
     * 显示fragment
     * @param activity Activity对象
     * @param fgmt BaseFragment对象
     * @param container fragment容器
     * @param bAddToStack 是否压栈
     */
    public static void showFragment(Activity activity, BaseFragment fgmt, int container, boolean bAddToStack)
    {
        if (activity == null || fgmt == null)
        {
            LogUtil.error(TAG, "showFragment activity or fgmt is null");
            return;
        }
        FragmentManager fm = activity.getFragmentManager();
        FragmentTransaction ft = fm.beginTransaction();
        View view = activity.getWindow().getDecorView();
        if (view != null)
        {
            showContainer(view, container);
            fgmt.setContainerId(container);
        }
        if (fgmt.isAdded())
        {
            ft.show(fgmt).commit();
            fm.executePendingTransactions();
        }
        else
        {
            if (bAddToStack)
            {
                fgmt.setPreFragment(lastFragment);
                if (lastFragment != null)
                {
                    //hideFragment(activity, lastFragment);
                    hideContainer(view, lastFragment.getContainerId());
                }
                ft.add(container, fgmt);
                ft.addToBackStack(null);
                /*
                 * java.lang.IllegalStateException: Can not perform this action
                 * after onSaveInstanceState
                 * 大致意思是说我使用的commit方法是在Activity的onSaveInstanceState
                 * ()之后调用的，这样会出错，因为onSaveInstanceState
                 * 方法是在该Activity即将被销毁前调用，来保存Activity数据的
                 * ，如果在保存玩状态后再给它添加Fragment就会出错。解决办法就 是把commit（）方法替换成
                 * commitAllowingStateLoss()就行了，其效果是一样的。
                 */
                ft.commitAllowingStateLoss();
            }
            else
            {
                ft.add(container, fgmt).commit();
            }
            fm.executePendingTransactions();
        }
    }

    /**
     * 隐藏fragment不需要container ID
     * @param activity Activity对象
     * @param fgmt BaseFragment对象
     */
    public static void hideFragment(Activity activity, BaseFragment fgmt)
    {
        if (activity == null || fgmt == null)
        {
            LogUtil.error(TAG, "hideFragment activity or fgmt is null");
            return;
        }
        FragmentManager fm = activity.getFragmentManager();
        View view = activity.getWindow().getDecorView();
        View vContainer;
        if (view != null)
        {
            int container = fgmt.getContainerId();
            vContainer = view.findViewById(container);
            if (fgmt instanceof BaseFragment && vContainer != null)
            {
                vContainer.setVisibility(View.GONE);
            }
        }
        if (fgmt.isAdded())
        {
            FragmentTransaction ftHide = fm.beginTransaction();
            ftHide.remove(fgmt);
            ftHide.commit();
        }
    }

    /**
     * 隐藏fragment需要container ID
     * @param activity Activity对象
     * @param fgmt BaseFragment对象
     * @param container fragment容器
     */
    public static void hideFragment(Activity activity, BaseFragment fgmt, int container)
    {
        if (activity == null || fgmt == null)
        {
            LogUtil.error(TAG, "hideFragment activity or fgmt is null");
            return;
        }
        FragmentManager fm = activity.getFragmentManager();
        View view = activity.getWindow().getDecorView();
        View vContainer;
        if (view != null)
        {
            vContainer = view.findViewById(container);
            if (vContainer != null)
            {
                vContainer.setVisibility(View.GONE);
            }
        }
        if (fgmt.isAdded())
        {
            FragmentTransaction ftHide = fm.beginTransaction();
            ftHide.remove(fgmt);
            ftHide.commit();
        }
    }

    /**
     * 显示fragment所在的container，fragment依然在container中
     * @param v 需要装在容器的视图
     * @param container fragment容器
     */
    public static void showContainer(View v, int container)
    {
        if (v == null)
        {
            LogUtil.trace(TAG, "showContainer v is null");
            return;
        }

        View vContainer = v.findViewById(container);
        if (vContainer != null)
        {
            vContainer.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 隐藏fragment所在的container，fragment依然在container中
     * @param v 需要装在容器的视图
     * @param container fragment容器
     */
    public static void hideContainer(View v, int container)
    {
        if (v == null)
        {
            LogUtil.trace(TAG, "hideContainer v is null");
            return;
        }

        View vContainer = v.findViewById(container);
        if (vContainer != null)
        {
            vContainer.setVisibility(View.GONE);
        }
    }

    /**
     * 弹出堆栈中最后一个fragment
     * @param fm BaseFragment对象
     */
    public static void popBackStack(FragmentManager fm)
    {
        if (fm == null)
        {
            LogUtil.error(TAG, "popBackStack fm is null");
            return;
        }
        fm.popBackStackImmediate();
        if (lastFragment != null)
        {
            Activity activity = lastFragment.getActivity();
            if (activity != null)
            {
                View v = activity.getWindow().getDecorView();
                showContainer(v, lastFragment.getContainerId());
            }
        }
    }

    /**
     * 弹出堆栈中所有fragment
     * @param fm BaseFragment对象
     */
    public static void popAllBackStack(FragmentManager fm)
    {
        boolean ret = false;
        if (fm == null)
        {
            LogUtil.error(TAG, "popAllBackStack fm is null");
            return;
        }
        do
        {
            try
            {
                ret = fm.popBackStackImmediate(null, 1);
            }
            catch (Exception e)
            {
                LogUtil.error(TAG, "popAllBackStack Exception");
            }
        }
        while (ret == true);
    }
}
